//
//  BoyHomePageController.m
//  WANNA
//
//  Created by lanou3g on 16/5/5.
//  Copyright © 2016年 浮夸. All rights reserved.
//

#import "BoyHomePageController.h"
#import "LDTNetWorkRequestManager.h"
#import "BHomePageModel.h"
#import "BHomePageCell.h"
#import "BHomeCycleModel.h"
#import "LDTCycleView.h"
#import "LORefresh.h"
#import "BhomeWebController.h"
@interface BoyHomePageController ()

///数据源数组
@property(nonatomic,strong)NSMutableArray *dataSource;
///轮播图属性
@property(nonatomic,strong)LDTCycleView *cycleView;
///存放轮播图的数组
@property(nonatomic,strong)NSMutableArray *cycleArray;

///请求内容起始条数
@property(nonatomic,strong)NSString *start;
//hader属性
@property(nonatomic,strong)LORefresh *headerRefresh;

@end

@implementation BoyHomePageController

- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray new];
    }
    return _dataSource;
}

- (NSMutableArray *)cycleArray
{
    if (!_cycleArray) {
        _cycleArray = [NSMutableArray new];
    }
    return _cycleArray;
}

- (void)dealloc
{
    //移除观察者
    [self.tableView removeObserver:[self.tableView defaultHeader]  forKeyPath:@"contentOffset"];  //gif图
    
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentSize"];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self getViews];
    self.start = @"1462272329";
    [self loadDataFromServerStart:self.start];
  
}

- (void)getViews
{
      [self.tableView registerNib:[UINib nibWithNibName:@"BHomePageCell" bundle:nil] forCellReuseIdentifier:@"cell"];
     [self.tableView dequeueReusableHeaderFooterViewWithIdentifier:@"headerView"];
    self.cycleView=[[LDTCycleView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 230) InterVal:3];
    
    [self.tableView addSubview:self.cycleView];


    
    //添加下拉刷新
    __weak typeof(self)weakSelf = self;
    [self.tableView addRefreshWithRefreshViewType:(LORefreshViewTypeHeaderDefault) refreshingBlock:^{
        
        [weakSelf.dataSource removeAllObjects];
        [weakSelf.tableView reloadData];
        [weakSelf loadDataFromServerStart:@"1462272329"];
    }];
    self.headerRefresh = [self.tableView defaultHeader];
    
    //上拉加载
    [self.tableView addRefreshWithRefreshViewType:(LORefreshViewTypeFooterDefault) refreshingBlock:^{
        
        NSInteger count = weakSelf.dataSource.count;
        weakSelf.start = [NSString stringWithFormat:@"%ld",count];
        
        [weakSelf loadDataFromServerStart:weakSelf.start];
        
    }];

    
}


- (void)loadDataFromServerStart:(NSString *)start
{
    NSData *dicData = [NSJSONSerialization dataWithJSONObject:@{@"ruleTime":self.start,@"curVersion":@"4.0.4",@"channelId":@"1",@"limit":@12,@"language":@"zh-Hans",@"refreshType":@1,@"ruleStartTime":@"1444642964",@"startTime":@0,@"localNum":@12,@"lastTime":@"1462272329"} options:NSJSONWritingPrettyPrinted error:nil];
    NSString *paras = [[NSString alloc]initWithData:dicData encoding:NSUTF8StringEncoding];
    NSString *parasStr = [paras stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet decimalDigitCharacterSet]];
    
    [LDTNetWorkRequestManager requestURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://new.yohoboys.com/yohoboyins/v4/channel/contentList?parameters=%@",parasStr]] Method:LDT_GET Params:nil
 Result:^(NSData *data, NSURLResponse *response, NSError *error) {
       
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
     
        
        NSDictionary *dict= jsonDict[@"data"][@"content"];
 
        for (NSDictionary *dic in dict) {
            BHomePageModel *model = [[BHomePageModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataSource addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            [[self.tableView defaultHeader]endRefreshing];
            [[self.tableView defaultFooter]endRefreshing];
        });
        
    }];
    
    NSData *dicData1 = [NSJSONSerialization dataWithJSONObject:@{@"channelId":@"1",@"curVersion":@"4.0.4",@"language":@"zh-Hans"} options:NSJSONWritingPrettyPrinted error:nil];
    
    NSString *paras1 = [[NSString alloc]initWithData:dicData1 encoding:NSUTF8StringEncoding];
    NSString *parasStr1 = [paras1 stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet decimalDigitCharacterSet]];

    [LDTNetWorkRequestManager requestURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://new.yohoboys.com/yohoboyins/v4/channel/banner?parameters=%@",parasStr1]] Method:LDT_GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array= jsonDict[@"data"];
        
        for (NSDictionary *dic in array) {
            BHomeCycleModel *model = [[BHomeCycleModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            
            UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.image]]];
            
            [self.cycleArray addObject:image];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            self.cycleView.imgNameArray = self.cycleArray;
        });
        
    }];

}


#pragma mark - Table view data source

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BhomeWebController *bhomeWebVC = [[BhomeWebController alloc]init];
    BHomePageModel *model = self.dataSource[indexPath.row];
    
    bhomeWebVC.publishUrl = model.publishURL;
    bhomeWebVC.titl = model.title;
    [self.navigationController pushViewController:bhomeWebVC animated:YES];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataSource.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BHomePageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.model =self.dataSource[indexPath.row];
    return cell;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
      UIView *headerView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 200)];
    
    tableView.tableHeaderView=headerView;
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 300;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
